<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_sponsor_bonus($sale_id){
/*
This function calculate the sponsor bonus for the sale id.
*/

	//globalize access to min_maintain
	global $vars;
	$db=$vars["db"];
	
	$sale = @mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$sale_id' and first_sale='y' and member_sale='y'"));
	if(!$sale){
		$result['status'] = false;
		$result['status'] = 'No sale with that ID found!';
		return $result;
	}elseif($sale['no_bv'] == 'y'){//no bv means this sale no need calculate bonus, purchase using maintenance
		$result['status'] = true;
		return $result;
	}
	
	$total_level=1;
	$level=1;
	$uid = $sale['uid'];
	$user = get_user_detail_by_id($uid);
	if(doubleval($user['rank_a']) == 4){//if user is platinum, sponsor bonus is paid back to the user himself
		$upline_id = $uid;
	}else{
		$upline_id=$user['ref'];
	}
	while($upline_id && $level<=$total_level){
		$r_upline=get_user_detail_by_id($upline_id);
		//upline only can receive comm if activated
		if($r_upline['activated']=='y'){
			$percent=$vars['product_ref_comm'];
			$comm_amount=round($sale['total_bv'] * $percent / 100, 2);
			//create comm record
			if(!mysql_query($sql="insert into $db->member_comm (cid, uid, from_uid, type, amount, percent, level, year, month, day, status, cdate) values 
			('$sale_id', '$upline_id', '$uid', 'r', '$comm_amount', '$percent', '$level', '".ndate('Y')."', '".ndate('n')."', '".ndate('j')."', 'confirmed', '".ndate()."')")){
				$errmsg.="Error creating the commission record for upline ID #$upline_id (level $level) for this sales. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}
			//credit to upline ewallet
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$comm_amount where id='$upline_id' limit 1")){
				$errmsg.="Error crediting $comm_amount of $vars[ewallet_title] to the member ID#$upline_id as sponsor commission. Please manually add back the amount to this member.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'credit', '$comm_amount', '".addslashes("Sponsor Commission received from downline ID#$post_s[uid] activation ".($r_user['rank_a']>0? "upgrade from {$vars['rank_index_a_d'][$r_user['rank_a']]} to $r_package_d[$refno]" : "for $r_package_d[$refno]"))."', '".ndate()."')")){
				$errmsg.="Error creating the $vars[ewallet_title] record history for the member ID#$upline_id as sponsor commission record. Please manually record this transaction by executing SQL.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$upline_id' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $comm_amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			//maintenance record
			$maintain_time=mktime(0, 0, 0, ndate('n')+1, 1, ndate('Y'));
			$maintain_year = date("Y", $maintain_time);
			$maintain_month = date("n", $maintain_time);
			$total_maintain_amount = $maintain_amount = round($comm_amount * $vars['maintenance_percent'] / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$upline_id' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;
			if($next_month_maintain < $vars['max_maintain']){
				if($maintain_amount + $next_month_maintain > $vars['max_maintain']){
					$maintain_amount = $vars['max_maintain'] - $next_month_maintain;
				}
				if(!mysql_query($sql="update $db->users set ewallet=ewallet-$maintain_amount, swallet=swallet+$maintain_amount where id='$upline_id' limit 1")){
					$errmsg.="Error deducting the maintenance amount of $maintain_amount and adding the $vars[swallet_title] of $maintain_amount from the member ID#$upline_id as maintenance. Please manually deduct /add the amount to this member.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
				}else{
					if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'debit', '$maintain_amount', '".addslashes("Debited ".number_format($maintain_amount, 2)." for maintenance, deducted from Sponsor Commission received from downline ID#$post_s[uid] activation ".($r_user['rank_a']>0? "upgrade from {$vars['rank_index_a_d'][$r_user['rank_a']]} to $r_package_d[$refno]" : "for $r_package_d[$refno]"))."', '".ndate()."')")){
						$errmsg.="Error creating the $vars[ewallet_title] record history for the member ID#$upline_id as maintenance. Please manually record this transaction by executing SQL.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$upline_id' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal -= $maintain_amount;
						@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
					if(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'credit', '$maintain_amount', '".addslashes("Credited ".number_format($maintain_amount, 2)." for maintenance, credited from Sponsor Commission received from downline ID#$post_s[uid] activation ".($r_user['rank_a']>0? "upgrade from {$vars['rank_index_a_d'][$r_user['rank_a']]} to $r_package_d[$refno]" : "for $r_package_d[$refno]"))."', '".ndate()."')")){
						$errmsg.="Error creating the $vars[swallet_title] record history for the member ID#$upline_id as maintenance. Please manually record this transaction by executing SQL.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$upline_id' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal += $maintain_amount;
						@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
				}
				if(!mysql_query($sql="insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate) values ('$upline_id', 'r', '$vars[maintenance_percent]', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')")){
					$critical_error.="Error creating the maintenance record for the member ID#$upline_id. Please manually create the maintenance record by executing SQL.<br /><br />$sql<br /><br />Error: ".mysql_error()."<br />";
				}
			}else{
				$maintain_amount = 0;
			}
			//mall point
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				if(!mysql_query($sql="update $db->users set ewallet=ewallet-$mall_point, mwallet=mwallet+$mall_point where id='$upline_id' limit 1")){
					$critical_error.="Error deducting the maintenance amount of $mall_point ($vars[mwallet_title]) and adding the $vars[mwallet_title] of $mall_point from the member ID#$upline_id. Please manually deduct /add the amount to this member.\n\n$sql\n\nError: ".mysql_error()."\n";
				}else{
					if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'debit', '$mall_point', '".addslashes("Debited ".number_format($mall_point, 2)." for maintenance, deducted from Sponsor Commission received from downline ID#$post_s[uid] activation ".($r_user['rank_a']>0? "upgrade from {$vars['rank_index_a_d'][$r_user['rank_a']]} to $r_package_d[$refno]" : "for $r_package_d[$refno]"))."', '".ndate()."')")){
						$critical_error.="Error creating the $vars[ewallet_title] record history for the member ID#$upline_id. Please manually record this transaction by executing SQL.\n\n$sql\n\nError: ".mysql_error()."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$upline_id' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal -= $mall_point;
						@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
					if(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'credit', '$mall_point', '".addslashes("Credited ".number_format($mall_point, 2)." for maintenance, credited from Sponsor Commission received from downline ID#$post_s[uid] activation ".($r_user['rank_a']>0? "upgrade from {$vars['rank_index_a_d'][$r_user['rank_a']]} to $r_package_d[$refno]" : "for $r_package_d[$refno]"))."', '".ndate()."')")){
						$critical_error.="Error creating the $vars[mwallet_title] record history for the member ID#$upline_id. Please manually record this transaction by executing SQL.\n\n$sql\n\nError: ".mysql_error()."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$upline_id' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal += $mall_point;
						@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
				}
				if(!mysql_query($sql="insert into $db->member_maintain (uid, type, comm_type, percent, amount, year, month, cdate) values ('$upline_id', 'm', 'r', '$vars[maintenance_percent]', '$mall_point', '$maintain_year', '$maintain_month', '".ndate()."')")){
					$critical_error.="Error creating the maintenance record ($vars[mwallet_title]) for the member ID#$upline_id. Please manually create the maintenance record by executing SQL.\n\n$sql\n\nError: ".mysql_error()."\n";
				}
			}
		}
		if($r_upline['ref']){
			$upline_id=$r_upline['ref'];
		}else{
			unset($upline_id);
		}
		$level++;
	}
	
	if($errmsg){
		$result['status'] = false;
		$result['errmsg'] = $errmsg;
	}else{
		$result['status'] = true;
	}
	
	return $result;
}
?>